//
//  GLHomeViewController.swift
//  GLWeiBo
//
//  Created by mac on 16/5/9.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
private let homeCellID = "homeCellID"
class GLHomeViewController: GLRootViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        prepareRefreshControl()
        //注册cell
        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: homeCellID)
        visitorView?.setupInfo("关注一些人，回这里看看有什么惊喜")
        // Do any additional setup after loading the view.
    }
    
    override func loadData() {
        let defaultIndex = 100
        //判断是否为上啦刷新
        let isPullup = refresh.isPullupRefresh
        refresh.beginRefreshing()
        //异步加载数据
        dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
            NSThread.sleepForTimeInterval(1.0)
            //下拉索引
            let pulldownIndex = isPullup ? 0 : (self.dataList.first ?? defaultIndex)
            //上啦刷新索引
            let pullupIndex = !isPullup ? 0 :(self.dataList.last ?? 0)
            print("下拉索引 \(pulldownIndex) 上拉索引 \(pullupIndex)")
            var arrayMu = [Int]()
            if !isPullup {
                for i in (0..<10).reverse() {
                    arrayMu.append(i + pulldownIndex + 1)
                    
                }
                
            }else{
                for i in 0..<10 {
                    arrayMu.append(pullupIndex-i-1)
                }
            }
            if isPullup {
                self.dataList += arrayMu
            } else{
                self.dataList = arrayMu + self.dataList
            }
            dispatch_async(dispatch_get_main_queue()) { () -> Void in
                self.refresh.endRefreshing()
                self.tableView.reloadData()
                
            }

        }
    }
    private lazy var dataList = [Int]()
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        if view.window == nil {
            dataList.removeAll()
            tableView.reloadData()
        }
        // Dispose of any resources that can be recreated.
    }
    


}
extension GLHomeViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataList.count
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(homeCellID, forIndexPath: indexPath)
        cell.textLabel?.text = dataList[indexPath.row].description
//        cell.textLabel?.text = "\(indexPath.row)"
        return cell
    }
}
